package com.example.kuaizu.service.imp;

import com.example.kuaizu.service.InFileUploadService;
import com.example.kuaizu.utils.FileUtils;
import kuaizu.common.constp.KuaiZuConst;
import kuaizu.common.exception.MassageException;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: wangmx15
 * @date: 2025/10/2
 **/
@Service
@RequiredArgsConstructor
public class FileUploadService implements InFileUploadService {

    @Autowired
    private final FileStorageService fileStorageService;
    private final FileUtils fileUtils;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @Override
    public String uploadImg(MultipartFile file) {
        //获取上传文件的名称
        String fileName = file.getOriginalFilename();
        //获取当前内存下的所有文件名称
        List<String> fileUrlList = fileUtils.listAllFileNames(KuaiZuConst.KUAIZU_IMG_URL);
        if (!CollectionUtils.isEmpty(fileUrlList)) {
            Map<String, String> fileNameMap = new HashMap<>();
            for (String fileurl : fileUrlList) {
                //只获取最后一个/后面的的内容
                String[] split = fileurl.split("/");
                fileNameMap.put(split[split.length - 1], fileurl);
            }
            //查看名字是否在map中
            if (fileNameMap.containsKey(fileName)) {
                throw new MassageException("文件名重复换一个名字");
            }
        }
        return  fileUtils.updateFile(file);


    }

    /**
     * 查询所有图片
     * @return
     */
    @Override
    public List<String> querImgList() {
        List<String> fileUrlList = fileUtils.listAllFileNames(KuaiZuConst.KUAIZU_IMG_URL);
        if (!CollectionUtils.isEmpty(fileUrlList)) {
            Map<String, String> fileNameMap = new HashMap<>();
            for (String fileurl : fileUrlList) {
                //只获取最后一个/后面的的内容
                String[] split = fileurl.split("/");
                fileNameMap.put(split[split.length - 1], fileurl);
            }
        }
        return fileUtils.listAllFileNames(KuaiZuConst.KUAIZU_IMG_URL);
    }

    /**
     * 删除图片
     * @param name
     */
    @Override
    public void deletimg(String name) {
        fileUtils.deleteFile(name,null);
    }


}
